package com.schedule.coursesystem;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.HashSet;
import java.util.Set;
import org.apache.poi.ss.usermodel.CellType;
import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/api/course")
public class CourseController {
    private static final File file = new File("courses.json");
    private static final ObjectMapper mapper = new ObjectMapper();
    private static List<Course> courseList = loadCourses();

    // 初始化时修复数据
    @PostConstruct
    public void init() {
        repairAndSaveCourses();
    }

    private void repairAndSaveCourses() {
        int repairedCount = 0;
        for (Course c : courseList) {
            if (c.id == null || c.id.trim().isEmpty()) {
                c.id = UUID.randomUUID().toString();
                repairedCount++;
            }
        }
        saveCourses();
        System.out.println("修复了 " + repairedCount + " 条无效ID记录");
    }

    private static List<Course> loadCourses() {
        try {
            if (!file.exists())
                return new ArrayList<>();

            // 读取课程数据
            List<Course> courses = mapper.readValue(file, new TypeReference<>() {});

            // 修复已存在的null ID
            for (Course c : courses) {
                if (c.id == null || c.id.trim().isEmpty()) {
                    c.id = UUID.randomUUID().toString();
                }
            }

            return courses;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    private static void saveCourses() {
        try {
            // 确保所有课程都有ID再保存
            for (Course c : courseList) {
                if (c.id == null || c.id.trim().isEmpty()) {
                    c.id = UUID.randomUUID().toString();
                }
            }
            mapper.writeValue(file, courseList);
        } catch (Exception ignored) {
        }
    }

    @PostMapping("/add")
    public String addCourse(@RequestBody Course course) {
        // 去重：同一用户、同一时间段、课程名、教师、地点、类型完全相同则不添加
        for (Course c : courseList) {
            if (c.userId.equals(course.userId)
                    && c.weekDay.equals(course.weekDay)
                    && c.period == course.period
                    && c.name.equals(course.name)
                    && c.teacher.equals(course.teacher)
                    && c.place.equals(course.place)
                    && c.type.equals(course.type)) {
                return "课程已存在";
            }
        }
        course.id = UUID.randomUUID().toString();
        courseList.add(course);
        saveCourses();
        return "课程添加成功";
    }

    @GetMapping("/list/{userId}")
    public List<Course> listCourses(@PathVariable String userId) {
        List<Course> result = new ArrayList<>();
        for (Course c : courseList) {
            if (c.userId.equals(userId))
                result.add(c);
        }
        return result;
    }

    @PostMapping("/import")
    public String importCourses(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) {
        try {
            List<Course> importedCourses = new ArrayList<>();
            // 创建用于去重的集合（基于课程关键特征）
            Set<String> duplicateCheckSet = new HashSet<>();

            // 加载现有课程到去重集合
            for (Course c : courseList) {
                if (c.userId.equals(userId)) {
                    String key = c.weekDay + "|" + c.period + "|" + c.name + "|" + c.teacher + "|" + c.place + "|" + c.type;
                    duplicateCheckSet.add(key);
                }
            }

            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int successCount = 0;
            int duplicateCount = 0;

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Course course = new Course();
                course.setUserId(userId);
                course.setName(getCellStringValue(row.getCell(0)));
                course.setTeacher(getCellStringValue(row.getCell(1)));
                course.setPlace(getCellStringValue(row.getCell(2)));
                course.setWeekDay(getCellStringValue(row.getCell(3)));

                // 处理节次单元格
                Cell periodCell = row.getCell(4);
                if (periodCell != null) {
                    if (periodCell.getCellType() == CellType.NUMERIC) {
                        course.setPeriod((int) periodCell.getNumericCellValue());
                    } else {
                        course.setPeriod(getCellStringValue(periodCell));
                    }
                }

                course.setType(getCellStringValue(row.getCell(5)));

                // 创建去重键（与addCourse相同的逻辑）
                String duplicateKey = course.weekDay + "|" + course.period + "|" +
                        course.name + "|" + course.teacher + "|" +
                        course.place + "|" + course.type;

                // 检查是否重复
                if (duplicateCheckSet.contains(duplicateKey)) {
                    duplicateCount++;
                    continue; // 跳过重复课程
                }

                // 通过检查后生成唯一ID
                course.id = UUID.randomUUID().toString();

                // 添加到导入列表和去重集合
                duplicateCheckSet.add(duplicateKey);
                importedCourses.add(course);
                successCount++;
            }

            // 批量添加非重复课程
            courseList.addAll(importedCourses);
            saveCourses();
            workbook.close();

            return String.format("导入完成！成功导入%d条，跳过%d条重复课程", successCount, duplicateCount);

        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败：" + e.getMessage();
        }
    }

    // 辅助方法：安全获取单元格字符串值
    private String getCellStringValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue().trim();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            // 对于整数型数值，去掉小数部分
            double num = cell.getNumericCellValue();
            if (num == (int) num) {
                return String.valueOf((int) num);
            }
            return String.valueOf(num);
        } else if (cell.getCellType() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == CellType.FORMULA) {
            // 处理公式单元格
            return cell.getCellFormula();
        }
        return "";
    }

    // 删除课程接口
    @PostMapping("/delete")
    public String deleteCourse(@RequestBody Course course) {
        // 根据userId和id删除指定课程
        boolean removed = courseList.removeIf(c -> c.userId.equals(course.userId) && c.id.equals(course.id));
        if (removed) {
            saveCourses();
            return "删除成功";
        } else {
            return "未找到课程，删除失败";
        }
    }

    // 更新课程接口
    @PostMapping("/update")
    public String updateCourse(@RequestBody Course course) {
        for (Course c : courseList) {
            if (c.userId.equals(course.userId) && c.id.equals(course.id)) {
                c.name = course.name;
                c.teacher = course.teacher;
                c.place = course.place;
                c.weekDay = course.weekDay;
                c.period = course.period;
                c.type = course.type;
                saveCourses();
                return "更新成功";
            }
        }
        return "未找到课程，更新失败";
    }
}